﻿using System;
using IListNode;

namespace JZ_22_lian_biao_zhong_dao_shu_di_kge_jie_dian_lcof
{
    class Program
    {
        static void Main (string[] args)
        {
            ListNode head = new ListNode (1);
            head.next = new ListNode (2);
            head.next.next = new ListNode (3);
            head.next.next.next = new ListNode (4);
            head.next.next.next.next = new ListNode (5);
            //head.next.next.next.next.next = null;
            head.next.next.next.next.next = new ListNode (6);
            head.next.next.next.next.next.next = null;

            ListNode end = GetKthFromEnd1 (head, 3);
            Display.DisplayListNode (end);
        }

        public static ListNode GetKthFromEnd (ListNode head, int k)
        {
            int count = 0;
            ListNode node = head;
            while (node != null)
            {
                count++;
                node = node.next;
            }

            while(count - k > 0)
            {
                head = head.next;
                count--; 
            }
            return head;
        }

        public static ListNode GetKthFromEnd1 (ListNode head, int k)
        {
            ListNode fast = head;
            ListNode slow = head;

            for (int i = 0;i < k-1;i++)
            {
                fast = fast.next;
            }
            while(fast.next != null)
            {
                fast = fast.next;
                slow = slow.next;
            }
            return slow;
        }
    }
}
